package com.mcxx.modules.system;

import com.alibaba.fastjson.JSONObject;
import com.mcxx.modules.system.dto.VisitLimitDTO;
import com.mcxx.redis.client.RedisClusterUtils;
import com.mcxx.service.DefaultRestService;
import com.mcxx.util.RSAUtils;
import com.yinhai.ta404.core.restservice.annotation.RestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.security.KeyPair;
import java.util.Date;



@Slf4j
@Validated
@Api(tags="救助系统访问控制类")
@RestService({"ops/visitLimit"})
public class VisitLimitController extends DefaultRestService {
    @Autowired
    private RedisClusterUtils redisClusterUtils;
    private final static String REDIS_CACHE_SUFFIX = "FUNC:";
    private final static String REDIS_LIMIT_SUFFIX = "LIMIT:";
    private final static String REDIS_RSA_SUFFIX = "RSA:";
    @Value("${society.rsa.priKeyPath:/home/hnsmzt/client/dist/references}")
    private String priKeyPath;
    @Value("${society.rsa.frontKeyPath:/home/hnsmzt/client/dist/references/references.json}")
    private String frontKeyPath;

    @PostMapping("add/IP")
    @ApiOperation(value="添加禁用IP")
    @ApiImplicitParams({
            @ApiImplicitParam(name="IP", value="禁用IP", required = true, paramType="query",dataType= "String"),
            @ApiImplicitParam(name="limitDate", value="禁用时间，永久填-1", required = true, paramType="query",dataType= "String"),
    })
    public void addLimitVisit(@RequestParam(required=true) String IP,
                               @RequestParam (required=true) Integer limitDate) {
        String limitKey = REDIS_CACHE_SUFFIX + REDIS_LIMIT_SUFFIX;
        VisitLimitDTO visitLimit = new VisitLimitDTO();
        visitLimit.setLimitStartTime(new Date());
        visitLimit.setLimitDate(limitDate);
        redisClusterUtils.hset(limitKey, IP, visitLimit);
        log.info("加入业务操作限制名单：{}", visitLimit);
        setData(visitLimit);
    }

    @PostMapping("remove/IP")
    @ApiOperation(value="删除禁用IP")
    @ApiImplicitParams({
            @ApiImplicitParam(name="IP", value="禁用IP", required = true, paramType="query",dataType= "String"),
    })
    public void removeLimitVisit(@RequestParam(required=true) String IP) {
        String limitKey = REDIS_CACHE_SUFFIX + REDIS_LIMIT_SUFFIX;
        redisClusterUtils.hdel(limitKey, IP);
        log.info("删除业务操作限制名单：{}", IP);
        setData("OK");
    }

    @PostMapping("rsa/generate")
    @ApiOperation(value="生成加密私/公钥")
    public void generateKeyPair() throws Exception {
        String limitKey = REDIS_CACHE_SUFFIX + REDIS_RSA_SUFFIX;
        KeyPair keyPair = RSAUtils.generateKeyPair();
        String privateKeyStr = new BASE64Encoder().encode(keyPair.getPrivate().getEncoded());
        String publicKeyStr = new BASE64Encoder().encode(keyPair.getPublic().getEncoded());
        redisClusterUtils.hset(limitKey, "PRI", privateKeyStr);
        redisClusterUtils.hset(limitKey, "PUB", publicKeyStr);


        File file = new File(priKeyPath + File.separator + "prikey_society");
        FileUtils.writeStringToFile(file, privateKeyStr, "UTF-8");


        file = new File(frontKeyPath);
        String content = FileUtils.readFileToString(file, "UTF-8");
        JSONObject json = JSONObject.parseObject(content);
        json.put("salt", publicKeyStr);
        FileUtils.writeStringToFile(file, json.toJSONString(), "UTF-8");

        setData("OK");
    }
}
